from selenium.webdriver.common.by import By

from .antd_page_element import AntdPageElement
from ...common.element_function import ElementFunction
from ...exception.TestException import TestException
from ...exception.errorcode import ErrorCode


class Radio(AntdPageElement):
    def setValue(self, value):
        """ 如果是指定的单选框组，则value填要选择哪一项，如果直接指定的label，value不管是什么都选择

        :param value:
        :return:
        """
        element = self._get_web_element()
        if 'ant-radio-group' in element.get_attribute('class'):
            radio_box_elements = self._find_radio_box_elements(element)
            for radio_box_element in radio_box_elements:
                name = self._get_radio_box_text(radio_box_element)
                if name == value:
                    ElementFunction(self._driver).click(radio_box_element)
                    if not self._is_checked(radio_box_element):
                        raise TestException.by_error_code(ErrorCode.ELEMENT_OPERATE_FAILED,
                                                          message='radio box {0} set checked failed'.format(value))
                    break
            else:
                raise TestException.by_error_code(ErrorCode.VALUE_NOT_FIND, value=value)
        elif 'ant-radio-wrapper' in element.get_attribute('class'):
            ElementFunction(self._driver).click(element)
            if not self._is_checked(element):
                raise TestException.by_error_code(ErrorCode.ELEMENT_OPERATE_FAILED,
                                                  message='radio box {0} set checked failed'.format(value))
            pass
        else:
            raise TestException.by_error_code(ErrorCode.UN_SUPPORT_ELEMENT, selector=str(element))

    def _is_checked(self, element):
        # 根据span找，更加准确点
        span_element = element.find_element(By.CSS_SELECTOR, 'span.ant-radio')
        return 'ant-radio-checked' in span_element.get_attribute('class')

    def _get_radio_box_text(self, element):
        # 直接取label元素的text，竟然可以！！！
        label = element.text
        return label.strip()

    def _find_radio_box_elements(self, element):
        selector = 'label.ant-radio-wrapper'
        return element.find_elements(By.CSS_SELECTOR, selector)

    def get_identification(self):
        identification = {'class': ['ant-radio-group', 'ant-radio-wrapper']}
        return identification
